﻿using Cysharp.Threading.Tasks;
using MessagePack;
using System.Collections.Generic;
using System.IO;

namespace DiverseStudents.Mods
{
    internal class ModPack
    {

        private const string packName = "packinfo";

        public IEnumerable<ModArchive> ReaderAll()
        {
            if ( DConfig.loadPath.Length > 0)
            {
                DirectoryInfo dir = new DirectoryInfo( DConfig.loadPath);
                DirectoryInfo[] subDirs = dir.GetDirectories();
                foreach (DirectoryInfo subDir in subDirs)
                {
                    var packPath = Path.Combine(subDir.FullName, packName);
                    if (File.Exists(packPath))
                    {
                        using (FileStream stream = new FileStream(packPath, FileMode.Open))
                        {
                            yield return MessagePackSerializer.Deserialize<ModArchive>(stream);
                        }
                    }
                }
            }
        }


        public async UniTask Writer(ModArchive archive)//统一为packt
        {
            if ( DConfig.loadPath.Length > 0)
            {
                var realPath = Path.Combine( DConfig.loadPath, archive.name);
                if (Directory.Exists(realPath))
                {
                    using (var steam = File.Create(Path.Combine(realPath, packName)))
                    {
                        await MessagePackSerializer.SerializeAsync(typeof(ModArchive), steam, archive);
                    }
                }
            }
        }
    }
}
